package me.zhengjie.tools.service.impl

import cn.hutool.extra.mail.Mail
import cn.hutool.extra.mail.MailAccount
import me.zhengjie.common.exception.BadRequestException
import me.zhengjie.common.utils.EncryptUtils.desDecrypt
import me.zhengjie.common.utils.EncryptUtils.desEncrypt
import me.zhengjie.tools.service.EmailService
import me.zhengjie.tools.repository.EmailRepository
import me.zhengjie.tools.domain.EmailConfig
import me.zhengjie.tools.domain.vo.EmailVo
import org.springframework.cache.annotation.CacheConfig
import org.springframework.cache.annotation.CachePut
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional

/**
 * @author Kuki Wu
 * @date 2018-12-26
 */
@Service
@CacheConfig(cacheNames = ["email"])
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = [Exception::class])
class EmailServiceImpl(private val emailRepository: EmailRepository) : EmailService {
    @CachePut(key = "'1'")
    @Transactional(rollbackFor = [Exception::class])
    override fun update(emailConfig: EmailConfig, old: EmailConfig?): EmailConfig {
        try {
            if (emailConfig.pass != old!!.pass) {
                // 对称加密
                emailConfig.pass = desEncrypt(emailConfig.pass)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return emailRepository.save(emailConfig)
    }

    @Cacheable(key = "'1'")
    override fun find(): EmailConfig? {
        val emailConfig = emailRepository.findById(1L)
        return emailConfig.orElseGet { EmailConfig() }
    }

    @Transactional(rollbackFor = [Exception::class])
    override fun send(emailVo: EmailVo?, emailConfig: EmailConfig?) {
        if (emailConfig == null) {
            throw BadRequestException("请先配置，再操作")
        }
        // 封装
        val account = MailAccount()
        account.host = emailConfig.host
        account.port = emailConfig.port!!.toInt()
        account.setAuth(true)
        try {
            // 对称解密
            account.pass = desDecrypt(emailConfig.pass)
        } catch (e: Exception) {
            throw BadRequestException(e.message)
        }
        account.from = emailConfig.user + "<" + emailConfig.fromUser + ">"
        // ssl方式发送
        account.isSslEnable = true
        val content = emailVo!!.content
        // 发送
        try {
            val size = emailVo.tos!!.size
            Mail.create(account)
                .setTos(*emailVo.tos!!.toTypedArray())
                .setTitle(emailVo.subject)
                .setContent(content)
                .setHtml(true) //关闭session
                .setUseGlobalSession(false)
                .send()
        } catch (e: Exception) {
            throw BadRequestException(e.message)
        }
    }
}